package com.travel.controller.admin;

import com.travel.model.entity.log.ApiLog;
import com.travel.service.Service.AdminDashboardService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//管理员登录接口 登录, 登出, 获取dashboard数据
@Controller
@RequestMapping("/admin")
@RequiredArgsConstructor
public class AdminLoginController {

    private final AdminDashboardService dashboardService;

    @GetMapping("/login")
    public String showLoginPage() {
        return "admin/login";
    }

    @GetMapping("/dashboard")
    public String showDashboard(Model model) {
        try {
            List<ApiLog> recentLogs = dashboardService.getRecentLogs();
            Map<String, Integer> apiStats = dashboardService.getApiStats();
            
            // 计算成功和失败次数
            long successCount = recentLogs.stream()
                .filter(log -> log.getStatusCode() < 400)
                .count();
            
            long errorCount = recentLogs.stream()
                .filter(log -> log.getStatusCode() >= 400)
                .count();
            
            model.addAttribute("apiStats", apiStats);
            model.addAttribute("recentLogs", recentLogs);
            model.addAttribute("successCount", successCount);
            model.addAttribute("errorCount", errorCount);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("apiStats", new HashMap<>());
            model.addAttribute("recentLogs", Collections.emptyList());
            model.addAttribute("successCount", 0);
            model.addAttribute("errorCount", 0);
            model.addAttribute("error", "获取统计数据失败：" + e.getMessage());
        }
        return "admin/dashboard";
    }

    @GetMapping("/logout")
    public String logout() {
        return "redirect:/admin/login?logout";
    }
} 